<?php
include_once (SYSTEM.'/Controller.php');
include_once (SYSTEM.'/Authencate.php');
require_once APPLICATION . '/Common/Captcha.php';
require_once APPLICATION . '/Models/AccountRepository.php';

class AccountController extends Controller
{		
	public function Register()
	{
		require APPLICATION . '/Models/RegisterModel.php';
		$this->ViewData['Title'] = 'Register';					
		$params = $this->GetParams();
				
		if(!isset($params['submit'])) 
		{
			$this->Render('Register','_Master');
		}
		else 
		{
			$accRep = new AccountRepository();
			$regModel = new RegisterModel($params);			
			$message = $regModel->ValidateFields();
			
			if(empty($message) && Captcha::Verify($params['captcha'])) 
			{								
				if(!$accRep->CheckUser($params['email']))
				{											
					$accRep->Register($regModel);
					$auObject = new Authencate();
	    			$auObject->SignIn(true,$params['email']);
					$this->Redirect('/Home/Index');
				}
				else 
				{
					$this->Render('Register', '_Master');
				}				
			}
			else 
			{
				$this->Render('Register', '_Master');
			}
		}		
	}

    public function Login()
    {
    	require APPLICATION . '/Models/LoginModel.php';
    	$this->ViewData['Title'] = 'Login';
    	
    	if(!isset($_SESSION['count']))
    		$_SESSION['count'] = 0;
    			
    	$params = $this->GetParams();    	
    	
    	if(!isset($params['login'])) 
    	{    		
         	$this->Render('Login', '_Master');
    	}
    	else 
    	{    		    		    	
    		$account = new AccountRepository();    		
    		
    		$user = new LoginModel($params);
    		$message = $user->ValidateFields();
    		
    		if(empty($message)) 
    		{    			
	    		if(!isset($params['captcha']))
	    		{
	    			if ($account->CheckLogin($params['email'], $params['password'])) 
	    			{
	    				$_SESSION['count'] = 0;
	    				$auObject = new Authencate();
	    				$auObject->SignIn(true,$params['email']);
	    				$this->Redirect('/Home/Index');	    				
	    			}
	    			else 
	    			{	    				
	    				$_SESSION['count']++;
	    				$this->Render('Login', '_Master');
	    			}
	    		}
	    		else if(isset($params['captcha']) && Captcha::Verify($params['captcha']))
	    		{
	    			if ($account->CheckLogin($params['username'], $params['password'])) 
	    			{
	    				$_SESSION['count'] = 0;
	    				$this->Redirect('/Home/Index');	    				
	    			}
	    			else 
	    			{    		
	    				$_SESSION['count']++;
	    				$this->Render('Login', '_Master');
	    			}
	    		}
	    		else 
	    		{    		
	    			$_SESSION['count']++;
	    			$this->Render('Login', '_Master');
	    		}
    		}
    		else 
    		{
    			$this->Render('Login', '_Master');
    		}
    	}
    }

    public function Delete()
    {
    	$account = new AccountRepository();
    	$account->Delete();
    	echo "Delete";
    }
}